package config

import (
	"fmt"
	"os"
	"bufio"
	"io"
	"strings"
)

const Latest = -1
const Path = "/etc/config.cfg"

var config = make(map[string]string)
var Conf = &Config{}

type Config struct {
	DebugSQL string

	DBEngine string
	DBDsn string


	Bind string `valid:"ipv4"`
	Port string `valid:"port"`

	HTTPProxy string

	Year string

}

func dsn(config map[string]string) string{
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true", config["DBUser"], config["DBPasswd"],
		config["DBServer"], config["DBName"])
	return dsn
}

//读取key=value类型的配置文件
func init() {
	f, err := os.Open(Path)
	defer f.Close()
	if err != nil {
		panic("open config.cfg failed.")
	}

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic("read config.cfg failed.")
		}
		s := strings.TrimSpace(string(b))
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}
		key := strings.TrimSpace(s[:index])
		if len(key) == 0 {
			continue
		} else {
			value := strings.TrimSpace(s[index+1:])
			if len(value) == 0 {
				continue
			}
			config[key] = value
		}
	}
	dsn := dsn(config)
	Conf.DBEngine = config["DBEngine"]
	Conf.DBDsn = dsn
	Conf.HTTPProxy = config["HTTPProxy"]
	Conf.Bind = config["Bind"]
	Conf.Port = config["Port"]
	Conf.DebugSQL = config["DebugSQL"]
	Conf.Year = config["Year"]
}